<?php
namespace Model;

use Core\Exception\BusinessException;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Predicate\Like;
use Zend\Db\Sql\Predicate\Operator;
use Zend\Db\Sql\Select;
use Zend\InputFilter\InputFilter;

class MenuItemTable extends AbstractTable
{

    /**
     * @param $id
     * @return MenuItem
     */
    public function getMenuItem($id){
       return $this->getById($id);
    }

    /**
     * @return InputFilter
     */
    public function getInputFilter()
    {
        $filter = new InputFilter();
        return $filter;
    }

    public function updateMenuItem($data,$id)
    {
        $menuItem_Item = $this->getMenuItem($id);
        if($menuItem_Item->modifiable == 0)
            throw new BusinessException("Không thể sửa menu item này. Vui lòng liên hệ admin.");
        $this->update($data,$id);
    }

    public function addMenuItem($data)
    {
        $parentId = $data["parentId"];
        $parentItem = $this->getMenuItem($parentId);
        $tmpData = $data;
        $tmpData["lft"] = $parentItem->rgt;
        $tmpData["rgt"] = $parentItem->rgt + 1;
        $this->reorderTree(  $parentItem->rgt - 1, $parentItem->menu_id);
        unset($tmpData["parentId"]);
        return $this->insert($tmpData);
    }

    private function reorderTree($lastRight, $menuId){
        $this->getTableGateway()->update(array('rgt'=>new Expression('rgt + 2')),
            array('rgt > '.$lastRight, 'menu_id'=>$menuId));

        $this->getTableGateway()->update(array('lft'=>new Expression('lft + 2')),
            array('lft > '.$lastRight, 'menu_id'=>$menuId));

    }

    public function removeMenuItem($id)
    {

        $menu_Item = $this->getMenuItem($id);
        //if iam a child
        if($menu_Item->lft == $menu_Item->rgt - 1){
            $this->reorderTreeOnDelete($menu_Item);
            $this->delete($id);

        }else{
            throw new BusinessException("Không được xóa menu có chứa menu con!");
        }
    }

    private function reorderTreeOnDelete($menuItem){
        $this->getTableGateway()->update(array('rgt'=>new Expression('rgt - 2')),
            array('rgt > '.$menuItem->rgt, 'menu_id'=>$menuItem->menu_id));

        $this->getTableGateway()->update(array('lft'=>new Expression('lft - 2')),
            array('lft > '.$menuItem->rgt, 'menu_id'=>$menuItem->menu_id));


    }
}